﻿using System.Collections.Generic;
using Infrastructure.ExternalService.Core.Role;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http;
using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.Responses;

namespace Infrastructure.ExternalService.Core.Imp.Role
{
    /// <summary>
    /// 角色查询服务
    /// </summary>
    public class RoleExternal : BaseHttpClient, IRoleExternal
    {
        private readonly OrderCenterApiOptions _orderingOptions;
        public IAccessTokenProvider TokenProvider { get; set; }

        public RoleExternal(IOptions<OrderCenterApiOptions> options,
            HttpClient client, ILoggerFactory loggerFactory)
            : base(client, loggerFactory, options.Value.RoleOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(RoleExternal)}配置获取失败");
            loggerFactory.CreateLogger<RoleExternal>();
        }

        /// <summary>
        /// 设置BaseHttpClient的BaseAddress：该值默认是从构造函数传入的，但重写该方法可以改变该值
        /// </summary>
        /// <returns></returns>
        protected override string SetHttpClientBaseAddress()
        {
            return null;
        }

        public async Task<IEnumerable<EmpInfo>> GetEmpByRoleId(GetEmpByRoleIdRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var response = await GetAsync<WrapResponse<GetEmpByRoleIdResponse>>(_orderingOptions.RoleOptions.GetUserListByRole
                                                                       + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {

                return response.Data.data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户的角色返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response.Msg}");
        }
    }
}